import 'package:flutter_ume_kit_mock/data/config_cache_manager.dart';
import 'package:flutter_ume_kit_mock/data/model/feishu_response.dart';
import 'dart:convert';
import 'package:flutter_ume_kit_mock/data/feishu_api.dart';
import 'package:flutter_ume_kit_mock/data/model/list_data.dart';
import 'package:dio/dio.dart';
import 'package:flutter_ume_kit_mock/widgets/mock_inspector.dart';

class ConfigService<T> {
  CacheType cacheType;
  ListData<T> Function(dynamic json) fromJsonT;
  String appToken;
  String tableId;

  ConfigService(this.cacheType, this.appToken, this.tableId, this.fromJsonT);

  Future<List<T>?> readCache() async {
    try {
      String? cacheJson = await ConfigCacheManager.readCache(cacheType);
      if (cacheJson == null || cacheJson.isEmpty) {
        return null;
      }
      return parseFromJson(jsonDecode(cacheJson)).data?.items;
    } catch (e) {
      print("${MockInspector.TAG} readCache $cacheType ${e.toString()}");
      return null;
    }
  }

  Future<List<T>?> fetchMockConfig(Dio dio, String token) async {
    try {
      Map<String, dynamic> caseResponse =
          await FeishuApi.fetchRecords(dio, token, appToken, tableId);
      ConfigCacheManager.writeCache(cacheType, jsonEncode(caseResponse));
      return parseFromJson(caseResponse).data?.items;
    } catch (e) {
      print("${MockInspector.TAG} fetchConfig $cacheType ${e.toString()}");
      return null;
    }
  }

  FeishuResponse<ListData<T>> parseFromJson(Map<String, dynamic> jsonMap) {
    return FeishuResponse<ListData<T>>.fromJson(jsonMap, fromJsonT);
  }
}
